<?php
namespace app\admin\model\auth;

use think\Model;
use think\model\relation\BelongsToMany;
use think\facade\Db;

class AdminModel extends Model
{
    protected $name = 'admins';
    // 主键
    protected $pk = 'id';
    protected $hidden = ['password'];
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    public function getLastLoginAtAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : null;
    }
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(
            RoleModel::class,
            'admin_role',
            'role_id',
            'admin_id'
        );
    }
    public function getAllPermissions($adminId): array
    {
        $adminId = (int)$adminId;
        if ($adminId === 1) {
            return MenuModel::where('type', 'in', [2, 3])
                ->where('status', 1)
                ->whereNotNull('permission')
                ->where('permission', '<>', '')
                ->column('permission');
        } else {
            $roleIds = Db::name('admin_role')->where('admin_id', $adminId)->column('role_id');
            if (empty($roleIds)) {
                return [];
            }
            $menuIds = Db::name('role_menu')->where('role_id', 'in', $roleIds)->column('menu_id');
            if (empty($menuIds)) {
                return [];
            }
            return MenuModel::where('id', 'in', array_unique($menuIds))
                ->where('type', 'in', [2, 3])
                ->where('status', 1)
                ->whereNotNull('permission')
                ->where('permission', '<>', '')
                ->column('permission');
        }
    }
}